<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="app">
        <div>
            <input type="text" v-model="inputVal">
            <button @click="addTodoFunc">添加todos</button>
            <button @click="addTodoAsyncFunc">异步添加todos</button>
        </div>
        <div>
            <h1>todos列表</h1>
            <div :key="item.id" v-for="(item,index) in this.$store.state.todos">
                    {{item.text}}
                <button @click="deleteTodo(index)">删除</button>
            </div>
        </div>
    </div>
</body>
<script src="./node_modules/vue/dist/vue.js"></script>
<script src="./node_modules/vuex/dist/vuex.js"></script>
<script>
    let store = new Vuex.Store({
        //创建store
        state:{
            todos:[
                {id:1, text:"土豆1"},
                {id:2, text:"土豆2"}
            ]
        },
        mutations:{
            addTode:function(state,todo){
                state.todos.push(todo)
            },
            //删除todos的操作
            deleteTodo:function(state,index){
                state.todos.splice(index,1)
            }
        },
        actions:{
            yibujia:function(context){
                //设置一个定时器,1秒之后才触发
                setTomeout(function(){
                    //假设let msg 的数值con后台返回
                    let msg = "苹果";
                    context.commit("addTodo",{
                        text:msg,
                        id:Date.now()
                    })
                },1000)
            }
        }    
    })
    //创建实例
    let vm = new Vue({
        el:"#app",
        data:{
            inputVal:"666",
        },
        store,
        methods:{
            addTodoFunc:function(){
                //当用户输入为空
                if(!this.inputVal){
                    alert("输入不能为空!!");
                    return false;
                }
                this.$store.commit("addTode",{
                    id:Date.now(),
                    text:this.inputVal,
                   
                });
            },
            deleteTodo:function(index){
                this.$store.commit("deleteTodo",index);
            },
            addTodoAsyncFunc:function(){
                //Vuex 触发异步操作 dispatch actions 
                this.$store.dispatch("yibujia")
            }
        }
    })
</script>
</html>